package com.zhao.dota.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.dota.config.ScheduledConfig;
import com.zhao.dota.mapper.SpringScheduledCronMapper;
import com.zhao.dota.model.SpringScheduledCron;
import com.zhao.dota.service.SpringScheduledCronService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SpringScheduledCronServiceImpl extends ServiceImpl<SpringScheduledCronMapper, SpringScheduledCron>
        implements SpringScheduledCronService {

    @Resource
    private ScheduledConfig scheduledConfig;

    @Override
    public boolean save(SpringScheduledCron springScheduledCron) {
        if (springScheduledCron.getId() == null) {
            springScheduledCron.setStatus(true);
            int insert = baseMapper.insert(springScheduledCron);
            scheduledConfig.addOrUpdateTask(springScheduledCron);
            return insert > 0;
        }
        springScheduledCron.setStatus(null);
        SpringScheduledCron old = getById(springScheduledCron.getId());
        BeanUtil.copyProperties(springScheduledCron, old, CopyOptions.create().ignoreNullValue());
        boolean b = updateById(old);
        if (old.getStatus()) {
            scheduledConfig.addOrUpdateTask(old);
        }
        return b;
    }

    @Override
    public boolean enable(Integer id) {
        SpringScheduledCron cron = getById(id);
        if (cron == null) {
            return false;
        }
        scheduledConfig.addOrUpdateTask(cron);
        return true;
    }

    @Override
    public boolean disable(Integer id) {
        SpringScheduledCron cron = getById(id);
        if (cron == null) {
            return false;
        }
        scheduledConfig.disableTask(id);
        return true;
    }


}
